/*
* Copyright (c)  2017, ueboot.com
* All rights reserved.
* 2017-10-29 11:39:14
*/
package com.ueboot.weishop.repository.order;

import com.ueboot.weishop.entity.order.OrderEntity;
import com.ueboot.core.repository.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by yangkui  on 2017-10-29 11:39:14.
 *
 * @author yangkui
 * @since 2.0 by autocode
 */
@Repository
public interface OrderRepository extends BaseRepository<OrderEntity, Long> {

	/**
	 * 根据订单号查询订单
	 *
	 * @param orderNo 订单号
	 * @return
	 */
	OrderEntity findByOrderNo(String orderNo);

	/**
	 * 根据一身份标识查询订单
	 * 用于当前活动针对客户限购的唯一身份标识，可以是openId,vin,mobile。具体由活动本身决定
	 * @param keyForLimit
	 * @return
	 */
	OrderEntity findBykeyForLimit(String keyForLimit);

	/**
	 * 根据用户ID分页和支付状态查询订单
	 *
	 * @param customerId 用户Id
	 * @return
	 */
	Page<OrderEntity> findByCustomerIdAndOrderStatus(Pageable pageable, Long customerId, String orderStatus);

	/**
	 * 根据用户ID查询订单(包括全部订单状态)
	 *
	 * @param customerId 用户Id
	 * @return
	 */
	List<OrderEntity> findByCustomerId(Long customerId);

	/**
	 * 根据用户ID分页查询订单(包括全部订单状态)
	 *
	 * @param customerId 用户Id
	 * @return
	 */
	Page<OrderEntity> findByCustomerId(Pageable pageable, Long customerId);

	/**
	 * 根据用户ID分页和和订单状态和退款申请状态查询（支付中和未支付的订单）
	 *
	 * @param customerId 用户Id
	 * @return
	 */
	Page<OrderEntity> findByCustomerIdAndOrderStatusAndRefundStatus(Pageable pageable, Long customerId, String orderStatus, String refundStatus);

	/**
	 * 根据用户ID分页和退款申请状态查询退款单
	 *
	 * @param customerId 用户Id
	 * @return
	 */
	Page<OrderEntity> findByCustomerIdAndRefundStatusNot(Pageable pageable, Long customerId, String refundStatus);

	@Modifying
	@Query("UPDATE #{#entityName} oe set oe.extStatus = :extStatusSet where oe.extStatus = :extStatusWhere and oe.orderStatus = :orderStatus and (categoryCode = :category1 or categoryCode = :category2)")
	int updateExtStatusByExtStatusAndOrderStatusAndCategory(@Param("extStatusSet") Integer extStatusSet, @Param("extStatusWhere") Integer extStatusWhere, @Param("orderStatus") String orderStatus, @Param("category1") String category1, @Param("category2") String category2);

	List<OrderEntity> findByExtStatusAndOrderStatus(Integer extStatus, String orderStatus);

	@Query(value = "select SEQ_WS_TABLE_SEQUENCE.nextval from dual", nativeQuery = true)
	BigDecimal getOrderNo();

	@Query(value="select * from WS_ORDER c where c.PAY_TIME >= to_date(:startTime,'yyyy-mm-dd hh24:mi:ss') and c.PAY_TIME <= to_date(:endTime,'yyyy-mm-dd hh24:mi:ss') order by id desc",
			nativeQuery = true)
	List<OrderEntity> findAllOrderEntityByTime(@Param("startTime") String startTime, @Param("endTime") String endTime);
}